﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace HousingDistribution
{
    class SpaceStandardProc
    {
        public DataTable Proc(bool upToStandard)
        {
            string sql = "select * from person, personSortInfo where person.idperson = personSortInfo.idperson";

            DataTable dt = DBProc.Instance().ReadData(sql).Tables[0];

            string housingInfoFieldName = DataDictionary.Instance().PersonTableFieldName(PersonColConsts.HOUSING_INFO);
            string gradeFieldName = DataDictionary.Instance().PersonSortInfoTableFieldName(PersonSortInfoColConsts.GRADE);

            List<HousingOccupancyInfo> housingInfo = new List<HousingOccupancyInfo>();
            foreach (DataRow dr in dt.Rows)
            {
                string housingInfoStr = dr[housingInfoFieldName].ToString();
                string grade = dr[gradeFieldName].ToString();

                housingInfo.Clear();
                housingInfoProc.ParseFromMySql(ref housingInfo, housingInfoStr);

                int area = GetHousingArea(housingInfo);
                int spaceStandard = DataDictionary.Instance().GetSpaceStandard(grade);

                //将不符合报表需求的项目删除
                if (((area >= spaceStandard) && upToStandard) || ((area < spaceStandard) && !upToStandard))
                {
                    
                }
                else
                {
                    dr.Delete();
                }
            }

            dt.AcceptChanges();

            return dt;
        }

        private int GetHousingArea(List<HousingOccupancyInfo> housingInfo)
        {
            if (housingInfo.Count == 0)
                return 0;

            StringBuilder sql = new StringBuilder("select * from housing where ");

            for(int i=0; i<housingInfo.Count-1; i++)
            {
                HousingOccupancyInfo info = housingInfo[i];
                sql.Append("idhousing ='");
                sql.Append(info.id);
                sql.Append("' or ");
            }

            sql.Append("idhousing ='");
            sql.Append(housingInfo[housingInfo.Count-1].id);
            sql.Append("'");

            DataTable dt = DBProc.Instance().ReadData(sql.ToString()).Tables[0];

            int area = 0;

            string areaFiledName = DataDictionary.Instance().HousingTableFieldName(HousingColConsts.AREA);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                area += Convert.ToInt16(dt.Rows[i][areaFiledName]);
            }

            return area;
        }

        HousingInfoProc housingInfoProc = new HousingInfoProc();
    }
}
